<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      button {
        margin: 10px 5px;
      }
      .top {
        border-bottom: 1px solid #ccc;
      }
      ul {
        list-style: none;
      }
    </style>
  </head>
  <body>
    <script src="./vue.js"></script>
    <div id="app">
      <div class="top">
        <button @click="list.push({...listData,id: Date.now()})">添加</button
        ><button @click="stopTimeAll()">
          {{stopAll?"全部开始":"全部暂停"}}
        </button>
      </div>
      <ul>
        <li v-for="(item,index) in list">
          <button @click="onTime(item)">开始</button>
          <button @click="stopTime(item)">暂停</button>
          <button @click="item.time=1,onTime(item)">重置时间间隔</button>
          <button @click="stopTime(item),del(index)">删除</button>
          <input
            type="text"
            placeholder="请输入时间间隔"
            v-model="item.time"
            @keydown.enter="onTime(item)"
          />秒
          <h1>{{item.num}}</h1>
        </li>
      </ul>
    </div>
    <script>
      new Vue({
        el: "#app",
        data: {
          list: [],
          listData: {
            num: 0,
            time: 1,
            isStop: true,
          },
        },
        methods: {
          onTime(item) {
            item.isStop = false;
            item.time = item.time ? item.time : 1;
            clearInterval(item.timer);
            item.timer = setInterval(function () {
              item.num++;
            }, item.time * 1000);
          },
          stopTime(item) {
            item.isStop = true;
            clearInterval(item.timer);
          },
          del(index) {
            this.list.splice(index, 1);
          },
          stopTimeAll() {
            if (this.stopAll) {
              this.list.forEach((v) => {
                this.onTime(v);
              });
            } else {
              this.list.forEach((v) => {
                this.stopTime(v);
              });
            }
          },
        },
        computed: {
          stopAll: {
            set(v) {
              this.list.forEach((v) => {
                v.isStop = v;
              });
            },
            get() {
              return this.list.every((v) => v.isStop);
            },
          },
        },
      });
    </script>
  </body>
</html>
